package au.com.iglootech.component;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.vaadin.terminal.StreamResource;

/**
 * generated PDF by template.
 * 
 * @author zhuhome
 * 
 */
public class IGTTemplatePDF implements StreamResource.StreamSource {
	/**
	 * 
	 */
	private static final long serialVersionUID = 481438782238784963L;

	private final transient ByteArrayOutputStream os = new ByteArrayOutputStream();

	private static final String ADDRESS = "Address";
	private static final String PATH = "template/invoice_template.pdf";

	/**
	 * 
	 * @param templatePath
	 *            path of template
	 */
	public IGTTemplatePDF(final String templatePath) {
		PdfStamper stamper = null;
		PdfReader pdfTemplate = null;

		try {

			InputStream is = IGTTemplatePDF.class.getClassLoader()
					.getResourceAsStream(PATH);
			pdfTemplate = new PdfReader(is);
			stamper = new PdfStamper(pdfTemplate, os);
			stamper.setFormFlattening(true);
			stamper.getAcroFields().setField(ADDRESS, "Ashwin Kumar");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stamper != null) {
				try {
					stamper.close();
				} catch (DocumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			pdfTemplate.close();
		}
	}

	@Override
	public final InputStream getStream() {
		// Here we return the pdf contents as a byte-array
		return new ByteArrayInputStream(os.toByteArray());
	}
}